/*
 * Created on 2005-2-28
 * Last modified on 2006-1-24
 * Powered by YeQiangWei.com
 */
package com.yeqiangwei.tools;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletInputStream;
import java.util.Dictionary;
import java.util.Hashtable;
import java.io.*;

@SuppressWarnings("unused")
public class FileUpLoad {
    // 定义变量，来获取上传文件名，路经等。
    private String savePath, filePath, fileName, contentType;
    private Dictionary fields; //表单输入数据名
    public String message;
    private boolean bea;
    public String getMessage(){
        return this.message; //用来采集程序执行过程中的信息
    }
    public boolean getBea(){
        return this.bea; //判断是否成功被上传
    }
    public String getFileName(){
        return fileName; //文件名
    }
    public String getFilePath(){
        return filePath; //文件路径
    }
    public String getContentType(){
        return contentType; // 文件类型
    }
    // 设置上传路径
    public void setSavePath(String savePath){
        this.savePath = savePath;
    }
    public String getFieldValue(String fieldName){
        if(fields == null || fieldName == null)
            return null; // 获取表单输入的数据
       return(String) fields.get(fieldName);
    }
    private void setFileName(String s){
        if(s==null) return ; // 从原始字节数据提取文件路径以及文件名
        int pos = s.indexOf("fileName=\"");
        if(pos != -1){
            filePath = s.substring(pos+10, s.length()-1);
            //windows 浏览器发送完整的路径和名字
            pos = filePath.lastIndexOf("\\");
            if(pos !=-1){
                fileName = filePath.substring(pos+1);
            }else{
                fileName = filePath;
            }
        }
    }
    private void setContentType(String s){
        if(s==null) return; //设置上传文件类型
        int pos = s.indexOf("：");
        if(pos!=-1) contentType = s.substring(pos+2, s.length());
    }
    @SuppressWarnings("unchecked")
	public void doUpload(HttpServletRequest request) throws IOException{
        ServletInputStream in = request.getInputStream();
        byte[] line = new byte[128];
        int i = in.readLine(line,0,128);
        //长度小于3 则可认为出错。
        if(i<3){
            message = "意外错误，请重新尝试！";
            bea = false;
            return;
        }
        //丢弃byte数组line的最后2个回车换行符
        int boundaryLength = i-2;
        String boundary = new String(line, 0, boundaryLength);
        //Hashtable对象将用来保存html表单元素名'
        fields = new Hashtable();
         message = "上传啦!" + String.valueOf(in)+ "////" + String.valueOf(fields);
        while(i !=-1){
            String newLine = new String(line,0,i);
            if(newLine.startsWith("Content-Disposition:form-data;name=\"")){
                 if(newLine.indexOf("fileName=\"")!=-1){
                    String ffname = new String(line,0,i-2); //
                    setFileName(ffname);//设置上传文件名
                    if(fileName==null) return;
                    //文件内容
                    i = in.readLine(line,0,128);
                    setContentType(new String(line,0,i-2));
                    i = in.readLine(line,0,128);
                    //空行
                    i = in.readLine(line,0,128);
                    newLine = new String(line,0,i);
                    PrintWriter pw = new PrintWriter(new BufferedWriter(
                    new FileWriter((savePath==null ? " " : savePath) + fileName )));
                    while(i!=-1 && !newLine.startsWith(boundary)){
                        //文件最后一行包括换行符，因此必须检查当前行是否是最后一行
                        i = in.readLine(line,0,128);
                        if((i==boundaryLength+2 || i==boundaryLength+4)
                            &&(new String(line,0,i).startsWith(boundary))){
                                pw.print(newLine.substring(0,newLine.length()-2));
                        }else{
                            pw.print(newLine);
                            newLine = new String(line,0,i);
                        }
                        pw.close();
                    }
                }else{
                        //普通表单输入元素
                    int pos = newLine.indexOf("name=\"");
                    String fieldName = newLine.substring(pos+6,newLine.length()-3);
                    i = in.readLine(line,0,128);
                    i = in.readLine(line,0,128);
                    newLine = new String(line,0,i);
                    StringBuffer fieldValue = new StringBuffer(128);
                    //最后以行换行符，因此必须检查当前行是否为最后以行；
                    i = in.readLine(line,0,128);
                    if((i==boundaryLength+2 || i==boundaryLength+4)
                        &&(new String(line,0,i).startsWith(boundary))){
                        fieldValue.append(newLine.substring(0,newLine.length()-2));
                    }else{
                        fieldValue.append(newLine);
                        newLine = new String(line,0,i);
                    }
                    fields.put(fieldName, fieldValue.toString());
               }
            }
            i = in.readLine(line,0,128);
        }       
    }
    
}
